package com.zhiche.lisa.bms.service.psup.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zhiche.lisa.bms.dao.model.fee.FeePayable;
import com.zhiche.lisa.bms.pojo.dto.fee.ShipParamDTO;
import com.zhiche.lisa.bms.pojo.dto.util.LspBasicDTO;
import com.zhiche.lisa.bms.pojo.dto.util.integration.ShipTaskDTO;
import com.zhiche.lisa.bms.pojo.dto.util.mdm.TransportationTypeDTO;
import com.zhiche.lisa.bms.service.fee.FeePayableService;
import com.zhiche.lisa.bms.service.price.PricePurchaseService;
import com.zhiche.lisa.bms.service.psup.SdBaseComputerService;
import com.zhiche.lisa.bms.service.psup.SdBaseFeePaybleFleet;
import com.zhiche.lisa.bms.service.utils.LspUtil;
import com.zhiche.lisa.bms.service.utils.MdmUtil;
import com.zhiche.lisa.bms.service.utils.OtmUtil;
import com.zhiche.lisa.bms.utils.ToolCommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author linbao
 * @date 2019-07-02
 */
@Service
@Slf4j
public class SdBaseFeePaybleFleetImpl implements SdBaseFeePaybleFleet {

    @Autowired
    private FeePayableService feePayableService;

    @Autowired
    private SdBaseComputerService sdBaseComputerService;

    @Autowired
    private PricePurchaseService pricePurchaseService;

    @Autowired
    private OtmUtil otmUtil;

    @Autowired
    private MdmUtil mdmUtil;

    @Autowired
    private LspUtil lspUtil;

    /**
     * 处理人送制定车队信息
     *
     * @param shipParamDTO
     */
    @Override
    public void dealSdFleetFeePayble(ShipParamDTO shipParamDTO) {
        FeePayable createFeePayable = getCreateFee(shipParamDTO);
        // 判断是否存在 - 存在就更新
        boolean isExist = updateExistFee(createFeePayable);
        if (!isExist) {

            // 更新人送价格
            sdBaseComputerService.computerFeePayableSendByDriver(createFeePayable);
            //去除价格里程的空值
            if (Objects.isNull(createFeePayable.getKilometre())) {
                createFeePayable.setKilometre(BigDecimal.ZERO);
            }
            if (Objects.isNull(createFeePayable.getActualPrice())) {
                createFeePayable.setActualPrice(BigDecimal.ZERO);
            }
            if (Objects.isNull(createFeePayable.getEstPrice())) {
                createFeePayable.setEstPrice(BigDecimal.ZERO);
            }
            if (Objects.isNull(createFeePayable.getActualAmt()) || BigDecimal.ZERO.compareTo(createFeePayable.getActualAmt()) == 0) {
                createFeePayable.setActualAmt(createFeePayable.getKilometre().multiply(createFeePayable.getActualPrice()));
            }
            createFeePayable.setEstAmt(createFeePayable.getKilometre().multiply(createFeePayable.getEstPrice()));


            if (createFeePayable.getVin() != null && createFeePayable.getActualPrice() != null && createFeePayable.getActualPrice().compareTo(BigDecimal.ZERO) > 0) {
                pricePurchaseService.updateExtPurchasePriceByItemUidNoTenant(createFeePayable);
            }

            // 新增
            feePayableService.insert(createFeePayable);
        }

    }


    /**
     * 是否存在
     *
     * @param createFeePayable
     * @return
     */
    private boolean updateExistFee(FeePayable createFeePayable) {
        boolean isExist = false;
        EntityWrapper<FeePayable> ew = new EntityWrapper<>();
        ew.eq("waybill_dtl_id", createFeePayable.getWaybillDtlId());
        ew.ne("status", 2);
        List<FeePayable> feePayableList = feePayableService.selectListNoTenant(ew);
        if (CollectionUtils.isNotEmpty(feePayableList)) {
            FeePayable existFeePayable = feePayableList.get(0);
            // 起运地
            existFeePayable.setStartName(createFeePayable.getStartName());
            // 目的地
            existFeePayable.setEndName(createFeePayable.getEndName());
            // 业务主体 - 客户
            existFeePayable.setCiamsId(createFeePayable.getCiamsId());
            // 发运时间
            existFeePayable.setOrderDate(createFeePayable.getOrderDate());
            // 发运状态
            if ("0".equals(existFeePayable.getLoadStatus())) {
                existFeePayable.setLoadStatus("20");
            }
            feePayableService.updateById(existFeePayable);
            isExist = true;
        }
        return isExist;
    }

    /**
     * 数据转换
     *
     * @param shipParamDTO
     * @return
     */
    private FeePayable getCreateFee(ShipParamDTO shipParamDTO) {
        // 数据转换
        FeePayable feePayable = new FeePayable();
        // 车牌号
        feePayable.setVehicleTypeName(shipParamDTO.getPlateNo());
        feePayable.setWaybillId(shipParamDTO.getShipCode());
        // 唯一运单号
        feePayable.setWaybillDtlId(shipParamDTO.getOrderReleaseId());
        // 指令号
        feePayable.setOrderCode(shipParamDTO.getShipmentId());
        // 运输方式
        feePayable.setTransTypeId(shipParamDTO.getTransTypeId());
        // 车型
        feePayable.setVehicleTypeCode(shipParamDTO.getVehicleName());
        // 车架号
        feePayable.setVin(shipParamDTO.getVin());
        // 起运省-市-区-低
        feePayable.setStartProvince(shipParamDTO.getOriginProvince());
        feePayable.setStartCity(shipParamDTO.getOriginCity());
        feePayable.setStartCounty(shipParamDTO.getOriginCounty());
        feePayable.setStartAddr(shipParamDTO.getOriginAddr());
        // 目的省-市-区-低
        feePayable.setEndProvince(shipParamDTO.getDestProvince());
        feePayable.setEndCity(shipParamDTO.getDestCity());
        feePayable.setEndCounty(shipParamDTO.getDestCounty());
        feePayable.setEndAddr(shipParamDTO.getDestAddr());

        // 发运时间
        if (StringUtils.isEmpty(shipParamDTO.getOccurDate())) {
            feePayable.setOrderDate(shipParamDTO.getShipTime());
        } else {
            Date shipDate = ToolCommonUtils.getDateByStr(shipParamDTO.getOccurDate(), ToolCommonUtils.FORMAT_PARTTEN_ONE);
            if (Objects.nonNull(shipDate)) {
                feePayable.setOrderDate(shipDate);
            }
        }
        // 客户运单号
        feePayable.setCusOrderNo(shipParamDTO.getCusOrderNo());
        feePayable.setCusWaybill(shipParamDTO.getCusWaybill());
        feePayable.setPayerId(Long.valueOf(shipParamDTO.getProviderGid()));
        feePayable.setPayerName(shipParamDTO.getProviderName());
        if (shipParamDTO.getDriverGid() != null) {
            feePayable.setDriverId(Long.valueOf(shipParamDTO.getDriverGid()));
        }
        feePayable.setDriverName(shipParamDTO.getDriverName());
        feePayable.setEndCounty(shipParamDTO.getDestCounty());
        feePayable.setFleetName(shipParamDTO.getFleetName());
        feePayable.setFleetId(Long.valueOf(shipParamDTO.getFleetId()));

        if (shipParamDTO.getTransTypeId() != null) {
            feePayable.setTransTypeId(shipParamDTO.getTransTypeId());
            TransportationTypeDTO transportTypeById = mdmUtil.getTransportTypeById(shipParamDTO.getTransTypeId());
            if (Objects.nonNull(transportTypeById) && StringUtils.isNotBlank(transportTypeById.getOtmValue())) {
                feePayable.setTransTypeName(transportTypeById.getOtmValue());
            }
        }
        // 运单状态
        if (shipParamDTO.getEventType() != null) {
            if ("BS_OP_DELIVERY".equals(shipParamDTO.getEventType())) {
                //10已发运
                feePayable.setLoadStatus("10");
            } else if ("BS_TRANS_ARRIVED".equals(shipParamDTO.getEventType())) {
                //30已运抵
                feePayable.setLoadStatus("30");
            }
        }
        //获取对应运单的客户
        List<ShipTaskDTO> otmShipmentDTL = otmUtil.getOtmShipmentDTL(feePayable.getOrderCode(), feePayable.getWaybillDtlId());
        if (CollectionUtils.isNotEmpty(otmShipmentDTL) && StringUtils.isNotBlank(otmShipmentDTL.get(0).getCiamsId())) {
            // 起运名称
            feePayable.setStartName(otmShipmentDTL.get(0).getOriginLocationName());
            // 目的名称
            feePayable.setEndName(otmShipmentDTL.get(0).getDestLocationName());
            // 业务主体
            feePayable.setCiamsId(otmShipmentDTL.get(0).getCiamsId());
        }
        // 租户id
        LspBasicDTO lspById = lspUtil.getLspById(feePayable.getPayerId());
        if (Objects.nonNull(lspById)) {
            feePayable.setTenantId(lspById.getTenantId());
        }
        return feePayable;
    }
}
